<?php
namespace app\lib\qiniu;

require_once '../vendor/qiniu/php-sdk/autoload.php';

use app\lib\exception\file\FileException;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\Exception;

class Qiniu
{
    private $auth;
    private $bucketManager;
    private $bucketName;
    private $accessKey;
    private $secretKey;
    private $domain;

    /**
     * 构造函数
     *
     * @param string $accessKey 七牛AccessKey
     * @param string $secretKey 七牛SecretKey
     * @param string $bucketName 空间名称
     */
    public function __construct($bucketName = null)
    {
        $this->accessKey = "Fxo_ez_SxoLppSGB_p6WViS9xTc6ii62YR66zBVZ";
        $this->secretKey = "nXShYVprxVq9N_VzAM5vFwRb8vgpQevW0FoueyZI";
        $this->bucketName = $bucketName;

        if ($bucketName == "yseh") {
            $this->domain = "https://www.youdnr.cn/";
        } elseif ($bucketName == "bjhvideo") {
            $this->domain = "http://www.nvhuangchina.cn/";
        } elseif ($bucketName == "guang1121") {
            $this->domain = "http://yaoyao.youdnr.cn/";
        }

        // 初始化认证对象
        $this->auth = new Auth($this->accessKey, $this->secretKey);

        // 初始化Bucket管理对象
        $this->bucketManager = new BucketManager($this->auth);
    }

    /**
     * 设置默认Bucket名称
     *
     * @param string $bucketName 空间名称
     */
    public function setBucket($bucketName)
    {
        $this->bucketName = $bucketName;
    }

    /**
     * 获取上传凭证
     *
     * @param string $bucketName 空间名称，如果为空则使用类初始化时的空间名
     * @param string $key 上传的文件名，可选
     * @param int $expires 凭证有效期，默认3600秒
     * @param array $policy 上传策略，可选
     * @return string 上传凭证
     */
    public function getUploadToken($bucketName = null, $key = null, $expires = 3600, $policy = null)
    {
        $bucket = $bucketName ?: $this->bucketName;
        if (empty($bucket)) {
            throw new Exception("Bucket name is required");
        }

        // 如果没有指定上传策略，使用默认策略
        if ($policy === null) {
            $policy = [
                'scope' => $key ? $bucket . ':' . $key : $bucket,
                'insertOnly' => 0, // 允许覆盖上传
            ];
        }

        return $this->auth->uploadToken($bucket, $key, $expires, $policy);
    }

    /**
     * 上传文件
     *
     * @param string $filePath 本地文件路径
     * @param string $key 上传到七牛的文件名
     * @param string $bucketName 空间名称，如果为空则使用类初始化时的空间名
     * @return string 上传结果
     */
    public function uploadFile($file)
    {

        // 要上传图片的本地路径
        $filePath = $file->getRealPath();
        $ext = pathinfo($file->getInfo('name'), PATHINFO_EXTENSION);  //后缀

        // 上传到七牛后保存的文件名
        $key = substr(md5($file->getRealPath()), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;

        $token = $this->getUploadToken($this->bucketName, $key);
        $uploadMgr = new UploadManager();

        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if ($err !== null) {
            return "";
        } else {
            return $this->domain.$ret['key'];
        }
    }

    public function foreverUrlUpload($url, $mykey=null)
    {
        $uploadMgr = new UploadManager();
        $imageContent = file_get_contents($url);

        // 获取HTTP头信息
        $headers = get_headers($url, 1);
        $extension = "";
        if ($headers && isset($headers['Content-Type'])) {
            $contentType = $headers['Content-Type'];

            // 根据Content-Type映射文件扩展名
            $mimeToExt = [
                'image/jpeg' => 'jpg',
                'image/jpg' => 'jpg',
                'image/png' => 'png',
                'image/webp' => 'webp',

                'video/mp4' => 'mp4',
                'video/quicktime' => 'mov',

                'audio/mpeg' => 'mp3',
                'audio/wav' => 'wav'
            ];

            $extension = $mimeToExt[$contentType] ?? '';
        }
        if ($extension == "") {
            return "文件类型不正确{$contentType}";
        }

        if ($mykey == null) {
            $key = md5($url . date('YmdHis') . rand(1000, 9999)) . $extension;
        } else {
            $key = $mykey;
        }
        $token = $this->getUploadToken($this->bucketName, $key);

        list($ret, $err) = $uploadMgr->put($token, $key, $imageContent);
        if ($err!== null) {
            return "上传失败";
        } else {
            return "http://yaoyao.youdnr.cn/".$ret['key'];
        }
    }

    /**
     * 删除文件
     *
     * @param string $key 要删除的文件名
     * @param string $bucketName 空间名称，如果为空则使用类初始化时的空间名
     * @return array 删除结果
     */
    public function deleteFile($key, $bucketName = null)
    {
        $bucket = $bucketName ?: $this->bucketName;
        if (empty($bucket)) {
            return ['success' => false, 'error' => 'Bucket name is required'];
        }

        list($ret, $err) = $this->bucketManager->delete($bucket, $key);

        if ($err !== null) {
            return ['success' => false, 'error' => $err];
        } else {
            return ['success' => true, 'data' => $ret];
        }
    }

    public function deleteFileBatch($keys, $bucketName = null)
    {
        $bucket = $bucketName ?: $this->bucketName;
        if (empty($bucket)) {
            return ['success' => false, 'error' => 'Bucket name is required'];
        }
        $ops = $this->bucketManager->buildBatchDelete($bucket, $keys);
        list($ret, $err) = $this->bucketManager->batch($ops);

        if ($err !== null) {
            return ['success' => false, 'error' => $err];
        } else {
            return ['success' => true, 'data' => $ret];
        }
    }
}
